package com.mall.admin.service;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.admin.exception.BusinessExceptio;
import com.mall.admin.exception.ErrorResult;
import com.mall.admin.interceptor.UserHolder;
import com.mall.domain.OmsOrder;
import com.mall.domain.OmsOrderItem;
import com.mall.domain.OmsOrderOperateHistory;
import com.mall.domain.UmsAdmin;
import com.mall.dto.OrderDeliveryDto;
import com.mall.dto.OrderMoneyDto;
import com.mall.dto.OrderPageDto;
import com.mall.dto.OrderReceiverDto;
import com.mall.interface1.api.OrderApi;
import com.mall.interface1.api.OrderItemApi;
import com.mall.interface1.api.OrderOperateHistoryApi;
import com.mall.interface1.api.UmsAdminApi;
import com.mall.vo.OrderDetailsVo;
import com.mall.vo.PageResult;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @DubboReference
    private OrderApi orderApi;

    @DubboReference
    private OrderOperateHistoryApi orderOperateHistoryApi;

    @DubboReference
    private OrderItemApi OrderItemApi;

    @DubboReference
    private UmsAdminApi umsAdminApi;

    //分页查询和条件查询订单详情
    public PageResult list(OrderPageDto dto) {
        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(dto, order);
        if (StringUtils.startsWith(dto.getReceiverKeyword(), "1")) {
            order.setReceiverPhone(dto.getReceiverKeyword());
        } else {
            order.setReceiverName(dto.getReceiverKeyword());
        }
        Page page = orderApi.pageOrder(dto.getPageNum(), dto.getPageSize(), order);
        if (page == null) {
            throw new BusinessExceptio(ErrorResult.error());
        }
        return new PageResult(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords());
    }

    //修改订单费用信息
    public void updateOrderMoney(OrderMoneyDto dto) {
        Long orderId = dto.getOrderId().longValue();
        if (orderApi.findById(orderId) == null) {
            throw new BusinessExceptio(ErrorResult.error());
        }
        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(dto, order);
        order.setId(orderId);
        order.setModifyTime(LocalDateTime.now());
        Integer count = orderApi.updateOrder(order);
        if (count != null) {
            UmsAdmin umsAdmin = umsAdminApi.query(UserHolder.getUserId());
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(LocalDateTime.now());
            history.setOrderStatus(0);
            history.setNote("修改订单费用信息");
            history.setOperateMan(umsAdmin.getNickName());
            orderOperateHistoryApi.saveOne(history);
        }
    }

    //修改收货人信息
    public void updateOrderReceiver(OrderReceiverDto dto) {
        Long orderId = dto.getOrderId().longValue();
        if (orderApi.findById(orderId) == null) {
            throw new BusinessExceptio(ErrorResult.error());
        }
        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(dto, order);
        order.setId(orderId);
        order.setModifyTime(LocalDateTime.now());
        Integer count = orderApi.updateOrder(order);
        if (count != null) {
            UmsAdmin umsAdmin = umsAdminApi.query(UserHolder.getUserId());
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(LocalDateTime.now());
            history.setOrderStatus(0);
            history.setNote("修改收货人信息");
            history.setOperateMan(umsAdmin.getNickName());
            orderOperateHistoryApi.saveOne(history);
        }
    }

    //批量删除订单(逻辑删除)
    public Integer delete(List<Integer> ids) {
        List<Long> orderIds = ids.stream().map(id -> id.longValue()).collect(Collectors.toList());
        List<OmsOrder> orderList = orderApi.findByIds(orderIds);
        if (CollUtil.isEmpty(orderList)) {
            throw new BusinessExceptio(ErrorResult.error());
        }
        for (OmsOrder order : orderList) {
            order.setDeleteStatus(1);  //删除状态：0->未删除；1->已删除
        }
        return orderApi.updateOrderList(orderList);
    }

    //批量关闭订单
    public void close(Map map) {   // "ids"="12,23,18"
        List<Long> orderIds = new ArrayList<>();
        String idsStr = (String) map.get("ids");
        String[] split = idsStr.split(",");
        for (String id : split) {
            orderIds.add(Long.parseLong(id));
        }
        String note = (String) map.get("note");
        UmsAdmin umsAdmin = umsAdminApi.query(UserHolder.getUserId());
        List<OmsOrder> orderList = orderApi.findByIds(orderIds);
        if (CollUtil.isEmpty(orderList)) {
            throw new BusinessExceptio(ErrorResult.error());
        }
        for (OmsOrder order : orderList) {
            order.setStatus(4);
        }
        Integer count = orderApi.updateOrderList(orderList);
        if (count != null) {
            List<OmsOrderOperateHistory> historyList = new ArrayList<>();
            for (OmsOrder order : orderList) {
                OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                history.setOrderId(order.getId());
                history.setCreateTime(LocalDateTime.now());
                history.setNote(note);
                history.setOrderStatus(order.getStatus());
                history.setOperateMan(umsAdmin.getNickName());
                historyList.add(history);
            }
            orderOperateHistoryApi.save(historyList);
        }
    }

    //批量发货
    public void delivery(List<OrderDeliveryDto> list) {
        List<OmsOrder> orderList = new ArrayList<>();
        for (OrderDeliveryDto dto : list) {
            OmsOrder order = new OmsOrder();
            BeanUtils.copyProperties(dto, order);
            if (StringUtils.isNotEmpty(dto.getAddress())) {
                order.setReceiverDetailAddress(dto.getAddress());
            }
            order.setId(dto.getOrderId().longValue());
            order.setStatus(2);
            order.setDeliveryTime(LocalDateTime.now());
            orderList.add(order);
        }
        Integer count = orderApi.updateOrderList(orderList);
        if (count != null) {
            UmsAdmin umsAdmin = umsAdminApi.query(UserHolder.getUserId());
            List<OmsOrderOperateHistory> historyList = new ArrayList<>();
            for (OmsOrder order : orderList) {
                OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                history.setOrderId(order.getId());
                history.setCreateTime(LocalDateTime.now());
                history.setNote("完成发货");
                history.setOrderStatus(2);
                history.setOperateMan(umsAdmin.getNickName());
                historyList.add(history);
            }
            orderOperateHistoryApi.save(historyList);
        }
    }

    //根据订单id查询订单详情
    public OrderDetailsVo findById(Integer id) {
        Long orderId = id.longValue();
        OmsOrder order = orderApi.findById(orderId);
        List<OmsOrderOperateHistory> list = orderOperateHistoryApi.findOperateHistory(orderId);
        List<OmsOrderItem> orderItemList = OrderItemApi.findOrderItem(orderId);
        if (order == null) {
            throw new BusinessExceptio(ErrorResult.error());
        }
        return OrderDetailsVo.init(order, list, orderItemList);
    }

    //备注订单
    public Integer note(Map<String, String> map) {
        Long orderId = Long.parseLong(map.get("id"));
        String note = map.get("note");
        Integer orderStatus = Integer.parseInt(map.get("status"));
        UmsAdmin umsAdmin = umsAdminApi.query(UserHolder.getUserId());
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setNote(note);
        history.setOrderStatus(orderStatus);
        history.setCreateTime(LocalDateTime.now());
        history.setOperateMan(umsAdmin.getNickName());
        return orderOperateHistoryApi.saveOne(history);
    }
}

